package com.distribute.rest.service.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.distribute.rest.dao.JedisClient;
import com.distribute.rest.service.ItemService;
import com.distribute.common.pojo.DistributeResult;
import com.distribute.common.util.JsonUtils;
import com.distribute.mapper.DbItemDescMapper;
import com.distribute.mapper.DbItemMapper;
import com.distribute.pojo.DbItem;
import com.distribute.pojo.DbItemDesc;

/**
 * 宠物信息管理Service
 * <p>Title: ItemServiceImpl</p>
 * <p>Description: 
 * 宠物基本信息和宠物描述信息在redis中的数据格式为string string的值为格式化后的json字符串
 * </p>
 * @version 1.0
 */
@Service
public class ItemServiceImpl implements ItemService {

	@Autowired
	private DbItemMapper itemMapper;
	
	@Autowired
	private DbItemDescMapper itemDescMapper;
	
	@Value("${REDIS_ITEM_KEY}")
	private String REDIS_ITEM_KEY;
	@Value("${REDIS_ITEM_EXPIRE}")
	private Integer REDIS_ITEM_EXPIRE;
	
	@Autowired
	private JedisClient jedisClient;
	
	//获取宠物基本信息 
	@Override
	public DistributeResult getItemBaseInfo(long itemId) {
		try {
			//添加缓存逻辑
			//从缓存中取宠物信息，宠物id对应的信息
			String json = jedisClient.get(REDIS_ITEM_KEY + ":" + itemId + ":base");
			//判断是否有值
			if (!StringUtils.isBlank(json)) {
				//把json转换成java对象
				DbItem item = JsonUtils.jsonToPojo(json, DbItem.class);
				return DistributeResult.ok(item);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		//根据宠物id查询宠物信息
		DbItem item = itemMapper.selectByPrimaryKey(itemId);
		//使用distributeResult包装一下
		try {
			//把宠物信息写入缓存
			jedisClient.set(REDIS_ITEM_KEY + ":" + itemId + ":base", JsonUtils.objectToJson(item));
			//设置key的有效期
			jedisClient.expire(REDIS_ITEM_KEY + ":" + itemId + ":base", REDIS_ITEM_EXPIRE);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return DistributeResult.ok(item);
	}
	//获取宠物描述信息
	@Override
	public DistributeResult getItemDesc(long itemId) {
		//添加缓存
		try {
			//添加缓存逻辑
			//从缓存中取宠物信息，宠物id对应的信息
			String json = jedisClient.get(REDIS_ITEM_KEY + ":" + itemId + ":desc");
			//判断是否有值
			if (!StringUtils.isBlank(json)) {
				//把json转换成java对象
				DbItemDesc itemDesc = JsonUtils.jsonToPojo(json, DbItemDesc.class);
				return DistributeResult.ok(itemDesc);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		//创建查询条件
		DbItemDesc itemDesc = itemDescMapper.selectByPrimaryKey(itemId);
		
		try {
			//把宠物信息写入缓存
			jedisClient.set(REDIS_ITEM_KEY + ":" + itemId + ":desc", JsonUtils.objectToJson(itemDesc));
			//设置key的有效期
			jedisClient.expire(REDIS_ITEM_KEY + ":" + itemId + ":desc", REDIS_ITEM_EXPIRE);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return DistributeResult.ok(itemDesc);
	}

	
}
